//
//  AppLoader.m
//  iCodeMacRun
//
//  Created by Andrew Barry on 18/03/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "AppLoader.h"
#import "FlippedView.h"
#import "graphics.h"
#import "cencode.h"
#import "form.h"
#import "jvm.h"
#import "icmloader.h"

extern NSDictionary *gInitBreakpoints;
jscontext *runMain();

@implementation AppLoader

-(void)awakeFromNib {
//	jvm *mainJVM = [jvm new];
//	[mainJVM startupJava];
	NSBundle *mainBundle = [NSBundle mainBundle];
	NSDictionary *infoPlist = [mainBundle infoDictionary];
	NSString *appName = [infoPlist valueForKey:@"CFBundleName"];
	
	// update all menu items with new app name
	if (appName != nil) {
		NSMenu *mainMenu = [NSApp mainMenu];
		int menuCount = [mainMenu numberOfItems];
		for (int midx = 0; midx < menuCount; midx++) {
			NSMenuItem *appMenuItem = [mainMenu itemAtIndex:midx];
			
			NSMenu *appMenu = [appMenuItem submenu];
			int itemCount = [appMenu numberOfItems];
			for (int idx = 0; idx < itemCount; idx++) {
				NSMenuItem *item = [appMenu itemAtIndex:idx];
				NSString *title = [item title];
				
				NSString *newTitle = [title stringByReplacingOccurrencesOfString:@"NewApplication" withString:appName];
				if (newTitle != title) {
					[item setTitle:newTitle];
				}
			}
		}
	}

	NSString *icmCodePath = [[NSBundle mainBundle] pathForResource:@"icmcode" ofType:@"bin"];
	NSString *icmLinkPath = [[NSBundle mainBundle] pathForResource:@"icmlink" ofType:@"bin"];
	struct LoadedProgram *prog = icmload([icmCodePath UTF8String], [icmLinkPath UTF8String]);
//								  "/Users/andrew/Downloads/Samples/Hurkle/Hurkle.app/Contents/Resources/icmlink.bin");

	jscontext *cx = executeProgram(prog);
//	jscontext *cx = runMain();
	
	
	jsvalue form = jsget(cx, cx->slots[GLOBAL_UI], 0, "Form");
	jsvalue startup = jsget(cx, form, 0, "_startupForms");
	int count = jsgetint(cx, startup, 0, "length", 0);
	for (int idx = 0; idx < count; idx++) {
		jsvalue construct = jsgetelem(cx, startup, INT_TO_JSVAL(idx));
		jsvalue wnd = jsnew(cx, construct, nil, 0);
		jsinvokename(cx, wnd, "show", nil, 0);
	}
	
	
	/*
	connectDebugServer();
	
	initializeRuntime();
	
	// load the standard runtime extensions
	NSString *standardPath = [[NSBundle mainBundle] pathForResource:@"icmSysStandard" ofType:@"js"];
	NSString *standardContent = [NSString stringWithContentsOfFile:standardPath];
	runScript(@"icmSysStandard.js", standardContent);

	standardPath = [[NSBundle mainBundle] pathForResource:@"icmSysOSX" ofType:@"js"];
	standardContent = [NSString stringWithContentsOfFile:standardPath];
	runScript(@"icmSysOSX.js", standardContent);
	
	NSString *progPath = [[NSBundle mainBundle] pathForResource:@"program" ofType:@"plist"];
		
	NSString *codePath = [[progPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Code"];
	
	NSDictionary *program = [[NSDictionary alloc] initWithContentsOfFile:progPath];
	NSString *sourceFolder = codePath;
	
	if ([program objectForKey:@"jdbcdriver"]) {
		[jvmrun setJDBCDriver: [program objectForKey:@"jdbcdriver"]];
		[jvmrun setJDBCClass: [program objectForKey:@"jdbcclass"]];
		[jvmrun setJDBCConnection: [program objectForKey:@"jdbconnection"]];
	}
	
	NSArray *items = [program objectForKey:@"items"];
	for (int idx = 0; idx < [items count]; idx++) {
		NSString *name = [items objectAtIndex:idx];
		NSString *ext = [name pathExtension];
		if ([ext isEqualToString:@"js"]) {
			NSString *path = [sourceFolder stringByAppendingPathComponent:name];
			NSString *script = [NSString stringWithContentsOfFile:path];
			
			runScript(name, script);
		} else if ([ext isEqualToString:@"png"]) {
			NSString *path = [sourceFolder stringByAppendingPathComponent:name];
			NSImage *img = [[NSImage alloc] initWithContentsOfFile:path];
			[img setFlipped:YES];
			JSObject *boundImage = bindImage(cx, img);
			stuffGlobal([name stringByDeletingPathExtension], boundImage);
		}
	}

	NSMutableArray *startupWindows = [NSMutableArray new];
	
	// load up any windows
	for (int idx = 0; idx < [items count]; idx++) {
		NSString *name = [items objectAtIndex:idx];
		NSString *ext = [name pathExtension];
		if ([ext isEqualToString:@"jsfrm"]) {
			NSString *path = [sourceFolder stringByAppendingPathComponent:name];
			NSDictionary *form = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
			
			FormLoader *loader = [[FormLoader alloc] init];
			[loader compileForm:form  withFile: name];
			
			stuffGlobal([name stringByDeletingPathExtension], bindFormDefinition(cx, form));

			bool showAtLaunch = [[form objectForKey:@"startup"] boolValue];
			if (showAtLaunch) {
				[startupWindows addObject:form];
			}
		}
	}
	
	// create the startup windows
	for (int idx = 0; idx < [startupWindows count]; idx++) {
		NSDictionary *form = [startupWindows objectAtIndex:idx];
		FormLoader *loader = [[FormLoader alloc] init];
		NSWindow *wnd = [loader newWindow:form];
		JSObject *wndObj = [loader loadForm:form into:wnd];
		[loader startForm: wndObj];

		[wnd makeKeyAndOrderFront:self];
	}
	 */
}

-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication {
	return YES;
}

@end
